package gweb

import (
	"fmt"

	"github.com/gin-gonic/gin/binding"

	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
)

var (
	goRunMode              string
	ginEngine              *gin.Engine
	routers                []func(app *gin.RouterGroup)
	routersWithOutBasePath []func(app *gin.RouterGroup)
	middlewares            []gin.HandlerFunc
)

// Init 初始化应用
func Init(configPath string) {
	initViper(configPath)
	initLog()
	initCache()
	InitDB()
	//InitNdb()
	InitWeb()
	InitValidate()
}

// Run 运行服务
func Run() error {
	fmt.Println("hello")
	if len(middlewares) > 0 {
		for _, v := range middlewares {
			ginEngine.Use(v)
		}
	}
	if len(routers) > 0 {
		prefix := ginEngine.Group(viper.GetString("basePath"))
		{
			for _, v := range routers {
				v(prefix)
			}
		}
	}
	if len(routersWithOutBasePath) > 0 {
		prefix := ginEngine.Group("")
		{
			for _, v := range routersWithOutBasePath {
				v(prefix)
			}
		}
	}
	return ginEngine.Run(viper.GetString("addr"))
}

// InitValidate 初始化验证器
func InitValidate() {
	binding.Validator = &customValidator{}
}

// GetGinEngine 返回引擎，可以进行自主配置
func GetGinEngine() *gin.Engine {
	return ginEngine
}

// InitWeb 初始化web
func InitWeb() {
	if !viper.GetBool("debug") {
		gin.SetMode("release")
		ginEngine = gin.New()
	} else {
		ginEngine = gin.Default()
	}
	loadMiddleware()
}

// RegistryRoute 注册路由
func RegistryRoute(r func(app *gin.RouterGroup)) {
	routers = append(routers, r)
}

// RegistryRouteWithOutBasePath 注册路由不会自动加basePath
func RegistryRouteWithOutBasePath(r func(app *gin.RouterGroup)) {
	routersWithOutBasePath = append(routersWithOutBasePath, r)
}

// RegistryMiddleware 注册中间件
func RegistryMiddleware(m gin.HandlerFunc) {
	middlewares = append(middlewares, m)
}
